package com.robot.member.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.robot.member.client.CouponClient;
import com.robot.member.client.GoodsClient;
import com.robot.member.client.MerchantClient;
import com.robot.member.client.OrdersClient;
import com.robot.member.pojo.Cart;
import com.robot.member.pojo.CartDetails;
import com.robot.member.pojo.Member;
import com.robot.member.pojo.client.*;
import com.robot.member.pojo.vo.ShoppingCart;
import com.robot.member.pojo.vo.ShoppingCartDetails;
import com.robot.member.service.CartDetailsService;
import com.robot.member.service.CartService;
import com.robot.member.service.MemberService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import util.CheckUtil;
import util.IdWorker;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * cart控制器层
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private CartService cartService;
    @Autowired
    private CartDetailsService cartDetailsService;


    @Autowired
    private MerchantClient merchantClient;
    @Autowired
    private GoodsClient goodsClient;
    @Autowired
    private OrdersClient ordersClient;
    @Autowired
    private CouponClient couponClient;

    @Autowired
    private CheckUtil checkUtil;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private IdWorker idWorker;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * member表status 状态 0-禁用 1-启用
     */
    private String memberStatusEnable = "1";
    /**
     * member表is_plus 是否plus会员 0-游客/注册用户,1-付了一块钱->会员,2-付了198->plus会员
     */
    private String memberIsPlusZero = "0";
    private String memberIsPlusOne = "1";
    private String memberIsPlusTwo = "2";

    /**
     * orders表has_coupon=是否使用了优惠券 0-未使用 1-已使用
     */
    private String ordersDontUseCoupon = "0";
    private String ordersUseCoupon = "1";
    /**
     * 优惠券表status=   0-未使用 1-已使用 2-已过期
     */
    private String couponStatusNotUsed = "0";
    private String couponStatusAlreadyUsed = "1";
    private String couponStatusExpired = "2";

    /**
     * store表status 状态 0-禁用 1-启用
     */
    private String storeStatusEnable = "1";

    /**
     * goods表的on_sale 上下架状态 0-下架 1-上架
     */
    private String goodsOnSaleFailed = "0";
    private String goodsOnSaleSuccess = "1";
    /**
     * goods表status 审核状态  0-待审核 1-审核通过 2-审核未通过
     */
    private String goodsStatus = "0";
    private String goodsStatusSuccess = "1";
    private String goodsStatusFailed = "2";

    /**
     * 100码豆等于1块钱
     */
    @Value("${sys.orders.beansToPriceRate}")
    private int beansToPriceRate;
    /**
     * 1金豆等于1块钱
     */
    @Value("${sys.orders.goldenBeanToPriceRate}")
    private int goldenBeanToPriceRate;
    /**
     * 城市合伙人收益,指一次交易中城市合伙人获取的收益=总收益*40%
     */
    @Value("${sys.orders.agentRevenueRate}")
    private Double agentRevenueRate;
    /**
     * 手续费/提现的费率=小票金额*0.006
     */
    @Value("${sys.orders.feeRate}")
    private Double feeRate;
    /**
     * 会长收益费率
     */
    @Value("${sys.orders.presidentRate}")
    private Double presidentRate;
    /**
     * 付了一块钱->会员
     */
    @Value("${sys.member.vip1}")
    private String vip1;
    /**
     * 付了198->plus会员
     */
    @Value("${sys.member.vip2}")
    private String vip2;

    String flag = "flag";
    String statusCode = "code";
    String message = "message";


    /**
     * 会员查看所有店的购物车
     *
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public Result findCartsByMemberId() throws ParseException {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        Member memberInDb = memberService.findById(claims.getId());
        logger.info("memberInDb=" + memberInDb);
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断


        //购物车中间类,用于显示购物车详情
        ShoppingCart shoppingCart = new ShoppingCart();
        ShoppingCartDetails shoppingCartDetails = new ShoppingCartDetails();
        List<Cart> cartInDbList = cartService.findAllByMemberIdAndDeletedAtIsNullOrderByCreatedAtDesc(claims.getId());
        logger.info("cartInDbList=" + cartInDbList);
        if (cartInDbList.size() == 0) {
            logger.info("shoppingCart is null");
            shoppingCart.setShoppingCartDetails(new ArrayList<>());
        } else {
            List<ShoppingCartDetails> shoppingCartDetailsList = new ArrayList<>();
            List<CartDetails> cartDetailsList = new ArrayList<>();
            for (Cart cartInDb : cartInDbList) {
                List<CartDetails> cartDetailsInDb = cartDetailsService.findAllByCartIdAndDeletedAtIsNull(cartInDb.getId());
                for (CartDetails cartDetails : cartDetailsInDb) {
                    cartDetailsList.add(cartDetails);
                }
                shoppingCartDetails.setCart(cartInDb);
                shoppingCartDetails.setCartDetailsList(cartDetailsInDb);
                shoppingCartDetails.setRate(cartInDb.getRate());
                shoppingCartDetailsList.add(shoppingCartDetails);
            }
            shoppingCart.setShoppingCartDetails(shoppingCartDetailsList);
        }
        shoppingCart.setPlus(judgeIsPlus(memberInDb));
        return new Result(StatusCode.SUCCESS_QUERY, shoppingCart);
    }

    /**
     * 会员查看某一家店的购物车
     *
     * @return
     */
    @RequestMapping(value = "{storeId}", method = RequestMethod.GET)
    public Result findCartByStoreIdAndMemberId(@PathVariable String storeId) throws ParseException {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        Member memberInDb = memberService.findById(claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        Store storeInDb = JSON.parseObject(merchantClient.thirdFindStoreById(storeId), Store.class);
        logger.info("storeInDb=" + storeInDb);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR_STORE_DOES_NOTE_EXIST);
        }

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setPlus(judgeIsPlus(memberInDb));
        shoppingCart.setShoppingCartDetails(new ArrayList<>());
        Cart cartInDb = cartService.findByStoreIdAndMemberIdAndDeletedAtIsNull(storeId, claims.getId());
        logger.info("cartInDb=" + cartInDb);
        if (cartInDb == null) {
            logger.info("shoppingCart is null");
            return new Result(StatusCode.SUCCESS_QUERY, shoppingCart);
        }

        List<ShoppingCartDetails> shoppingCartDetailsList = new ArrayList<>();
        ShoppingCartDetails shoppingCartDetails = new ShoppingCartDetails();
        List<CartDetails> cartDetailsInDb = cartDetailsService.findAllByCartIdAndDeletedAtIsNull(cartInDb.getId());
        logger.info("The cartInDb is" + cartInDb + "and the cartDetailsInDb is" + cartDetailsInDb);
        shoppingCartDetails.setCart(cartInDb);
        shoppingCartDetails.setCartDetailsList(cartDetailsInDb);
        shoppingCartDetails.setRate(cartInDb.getRate());
        shoppingCartDetailsList.add(shoppingCartDetails);
        shoppingCart.setShoppingCartDetails(shoppingCartDetailsList);
        return new Result(StatusCode.SUCCESS_QUERY, shoppingCart);
    }

    /**
     * 会员将单个商品加入购物车
     *
     * @param searchMap
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public Result add(@RequestBody Map searchMap) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        //判断店铺
        String storeId = (String) searchMap.get("storeId");
        Store storeInDb = cartService.checkStore(storeId);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR, "店铺不存在");
        }

        //判断商品
        String goodsId = (String) searchMap.get("goodsId");
        Goods goodsInDb = cartService.checkGoods(goodsId, storeId);
        if (goodsInDb == null) {
            return new Result(StatusCode.ERROR, "商品不存在");
        }

        //判断商品数量
        Integer goodsSum = (Integer) searchMap.get("goodsSum");
        String message = cartService.checkGoodsSum(goodsSum, goodsInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        //单个商品数量=0表示去掉购物车中的该商品
        if (goodsSum == 0) {
            Cart cartInDb = cartService.findByStoreIdAndMemberIdAndDeletedAtIsNull(storeId, claims.getId());
            if (cartInDb == null || cartInDb.getId() == null) {
            } else {
                cartDetailsService.deleteByCartIdAndGoodsId(cartInDb.getId(), goodsId);
            }
            return new Result(StatusCode.SUCCESS_INSERTED);
        }

        LocalDateTime now = LocalDateTime.now();
        //更新购物车
        Cart cartInDb = cartService.updateCart(storeInDb, claims.getId(), now);

        //更新购物车详细
        CartDetails cartDetailsInDb = cartService.updateCartDetails(goodsInDb, cartInDb.getId(), goodsId, goodsSum, now);
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 会员将多个商品加减到购物车
     *
     * @param searchMap
     */
    @RequestMapping(value = "{storeId}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result update(@PathVariable String storeId, @RequestBody String searchMap) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        logger.info("searchMap=" + searchMap);
        //判断店铺
        Store storeInDb = cartService.checkStore(storeId);
        if (storeInDb == null) {
            return new Result(StatusCode.ERROR, "店铺不存在");
        }

        JSONObject jsonObject = JSONObject.parseObject(searchMap);
        JSONArray goodsArray = jsonObject.getJSONArray("goods");
        if (goodsArray.size() == 0) {
            //商品数量为0表示清空该购物车
            Cart cartInDb = cartService.findByStoreIdAndMemberIdAndDeletedAtIsNull(storeId, claims.getId());
            if (cartInDb == null || cartInDb.getId() == null) {
            } else {
                cartService.deleteAllByMemberId(claims.getId());
                cartDetailsService.deleteAllByCartId(cartInDb.getId());
            }
            return new Result(StatusCode.SUCCESS_INSERTED);
        }

        for (int i = 0; i < goodsArray.size(); i++) {
            JSONObject goods = goodsArray.getJSONObject(i);
            //判断商品
            String goodsId = (String) goods.get("goodsId");
            Goods goodsInDb = cartService.checkGoods(goodsId, storeId);
            if (goodsInDb == null) {
                return new Result(StatusCode.ERROR, "第" + (i + 1) + "件商品不存在");
            }

            //判断商品数量
            Integer goodsSum = (Integer) goods.get("goodsSum");
            String message = cartService.checkGoodsSum(goodsSum, goodsInDb);
            if (!"".equals(message)) {
                return new Result(StatusCode.ERROR, "第" + (i + 1) + "件商品,"+message);
            }

            logger.info("The member who's id=" + claims.getId() + " will add the goods which <goodsId=" + goodsId + " and goodsSum=" + goodsSum + "> to cart DB!");
            //单个商品数量=0表示去掉购物车中的该商品
            if (goodsSum == 0) {
                Cart cartInDb = cartService.findByStoreIdAndMemberIdAndDeletedAtIsNull(storeId, claims.getId());
                if (cartInDb == null || cartInDb.getId() == null) {
                } else {
                    cartDetailsService.deleteByCartIdAndGoodsId(cartInDb.getId(), goodsId);
                }
                continue;
            }

            LocalDateTime now = LocalDateTime.now();
            //更新购物车
            Cart cartInDb = cartService.updateCart(storeInDb, claims.getId(), now);

            //更新购物车详细
            CartDetails cartDetailsInDb = cartService.updateCartDetails(goodsInDb, cartInDb.getId(), goodsId, goodsSum, now);
        }
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 会员将购物车商品下单,适用于一家店
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "addCartToOrders", method = RequestMethod.POST)
    public Result addCartToOrders(@RequestBody String searchMap) throws ParseException {
        logger.info("searchMap=" + searchMap);
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        Member memberInDb = memberService.findById(claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对会员是否存在和状态进行判断

        JSONObject jsonObject = JSONObject.parseObject(searchMap);
        //判断收货地址
        String addressId = jsonObject.getString("addressId");
        String message = cartService.checkAddress(addressId, memberInDb.getId());
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        //从购物车下单则购物车肯定存在
        String cartId = jsonObject.getString("cartId");
        Cart cartInDb = cartService.checkCart(cartId);
        if (cartInDb == null) {
            return new Result(StatusCode.ERROR, "购物车不存在");
        }

        //通过购物车查找店铺
        String storeId = cartInDb.getStoreId();
        Store storeInDb = cartService.checkStore(storeId);
        if (storeId == null) {
            return new Result(StatusCode.ERROR_STORE_DOES_NOTE_EXIST);
        }

        //用于增加订单详细
        ArrayList<OrdersDetails> addOrdersDetailsList = new ArrayList<>();
        //用于更新购物车中商品数量
        ArrayList<CartDetails> updateCartDetailsList = new ArrayList<>();
        //用于删除购物车中商品数量<=0的商品
        ArrayList<CartDetails> deleteCartDetailsList = new ArrayList<>();
        //小票金额
        BigDecimal price = BigDecimal.ZERO;
        //实付金额
        BigDecimal payAmount = BigDecimal.ZERO;
        //优惠金额
        BigDecimal discountAmount = BigDecimal.ZERO;
        //折扣率
        Double rate = 0.0;
        //订单ID
        String ordersId = idWorker.nextId() + "";
        //子订单ID
        String subOrdersId = idWorker.nextId() + "";
        //新建总订单orders
        Orders orders = new Orders();

        LocalDateTime now = LocalDateTime.now();
        //判断并计算下单时购物车里的商品是否存在及数量
        JSONArray goodsArray = jsonObject.getJSONArray("goods");
        for (int i = 0; i < goodsArray.size(); i++) {
            JSONObject goods = goodsArray.getJSONObject(i);
            //判断商品
            String goodsId = (String) goods.get("goodsId");
            Goods goodsInDb = cartService.checkGoods(goodsId, storeId);
            if (goodsInDb == null) {
                return new Result(StatusCode.ERROR, "第" + (i + 1) + "件商品不存在");
            }

            //判断商品数量
            Integer goodsSum = (Integer) goods.get("goodsSum");
            message = cartService.checkGoodsSum(goodsSum, goodsInDb);
            if (!"".equals(message)) {
                return new Result(StatusCode.ERROR, "第" + (i + 1) + "件商品,"+message);
            }
            logger.info("The member who's id=" + memberInDb.getId() + "will add the goods which <goodsId=" + goodsId + "and goodsSum=" + goodsSum + ">to orders DB!");

            //实付金额temp,用来计算订单详情里的payAmount
            BigDecimal payAmountTemp = BigDecimal.ZERO;
            payAmountTemp = goodsInDb.getPrice().multiply(new BigDecimal(goodsSum));
            price = price.add(payAmountTemp);
            payAmount = payAmount.add(payAmountTemp);

            //增加订单详细
            addOrdersDetailsList = cartService.updateOrdersDetails(addOrdersDetailsList, goodsInDb, ordersId, subOrdersId, goodsSum, payAmountTemp, now);

            //修改购物车明细
            CartDetails cartDetailsInDb = cartDetailsService.findByCartIdAndGoodsIdAndDeletedAtIsNull(cartInDb.getId(), goodsId);
            if (cartDetailsInDb != null) {
                int sum = cartDetailsInDb.getGoodsSum() - Math.abs(goodsSum);
                if (sum <= 0) {
                    deleteCartDetailsList.add(cartDetailsInDb);
                } else {
                    cartDetailsInDb.setGoodsSum(sum);
                    updateCartDetailsList.add(cartDetailsInDb);
                }
            }
        }

        //使用优惠券
        Coupon couponInDb = new Coupon();
        String hasCoupon = jsonObject.getString("hasCoupon");
        String couponId = jsonObject.getString("couponId");
        if (hasCoupon != null && !"".equals(hasCoupon) && ordersUseCoupon.equals(hasCoupon)) {
            couponInDb = JSON.parseObject(couponClient.thirdFindCouponByIdAndMemberId(couponId, memberInDb.getId()), Coupon.class);

            orders.setHasCoupon(ordersUseCoupon);
            orders.setCouponId(couponInDb.getId());

            payAmount = payAmount.subtract(couponInDb.getPrice());
            discountAmount = discountAmount.add(couponInDb.getPrice());
            logger.info("use coupon and coupon id=" + couponInDb.getId() + ",and coupon's price=" + couponInDb.getPrice() + "and coupon's status=" + couponInDb.getStatus());
            couponInDb.setStatus(couponStatusAlreadyUsed);

        } else {
            logger.info("dont use coupon");
            orders.setHasCoupon(ordersDontUseCoupon);
        }
        logger.info("使用优惠券后小票金额1=" + price + "实付金额=" + payAmount + "优惠金额=" + discountAmount);

        //会员折扣
        if (!memberIsPlusZero.equals(memberInDb.getIsPlus())) {
            Double memberRate = getMemberRate(memberInDb.getIsPlus(), storeInDb.getRate());
            logger.info("memberRate=" + memberRate);
            if (memberRate != 0) {
                payAmount = payAmount.multiply(BigDecimal.valueOf(memberRate));
                if (payAmount.compareTo(BigDecimal.ZERO) == -1) {
                    return new Result(StatusCode.ERROR, "付款金额不能小于0");
                } else {
                    rate = memberRate;

                    discountAmount = price.subtract(payAmount);
                }
            }
        }
        logger.info("会员折扣后小票金额2=" + price + "实付金额=" + payAmount + "优惠金额=" + discountAmount);

        //使用码豆数量
        Integer beans = jsonObject.getInteger("beans");
        DecimalFormat decimalFormat = new DecimalFormat("0.000");
        logger.info("beans=" + beans);
        if (beans != null) {
            if (beans >= 0) {
                if (memberInDb.getBeans() - beans < 0) {
                    return new Result(StatusCode.ERROR, "码豆不足");
                }
                BigDecimal beansPrice = new BigDecimal(decimalFormat.format((double) beans / beansToPriceRate));
                logger.info("beansPrice=" + beansPrice);
                payAmount = payAmount.subtract(beansPrice);
                if (payAmount.compareTo(BigDecimal.ZERO) == -1) {
                    return new Result(StatusCode.ERROR, "码豆可抵金额大于订单金额");
                }
                orders.setBeans(beans);
                discountAmount = discountAmount.add(beansPrice);
            } else {
                return new Result(StatusCode.ERROR, "使用的码豆数量必须是大于0的正整数");
            }
        } else {
            beans = 0;
        }
        logger.info("使用码豆后小票金额3=" + price + "实付金额=" + payAmount + "优惠金额=" + discountAmount);

        //使用金豆数量
        Integer goldenBeans = jsonObject.getInteger("goldenBeans");
        logger.info("goldenBeans=" + goldenBeans);
        if (goldenBeans != null) {
            if (goldenBeans >= 0) {
                if (memberInDb.getGoldenBeans() - goldenBeans < 0) {
                    return new Result(StatusCode.ERROR, "金豆不足");
                }
                BigDecimal goldenBeansPrice = new BigDecimal(decimalFormat.format((double) goldenBeans / goldenBeanToPriceRate));
                logger.info("goldenBeansPrice=" + goldenBeansPrice);
                payAmount = payAmount.subtract(goldenBeansPrice);
                if (payAmount.compareTo(BigDecimal.ZERO) == -1) {
                    return new Result(StatusCode.ERROR, "金豆可抵金额大于订单金额");
                }
                orders.setGoldenBeans(goldenBeans);
                discountAmount = discountAmount.add(goldenBeansPrice);
            } else {
                return new Result(StatusCode.ERROR, "使用的金豆数量必须是大于0的正整数");
            }
        } else {
            goldenBeans = 0;
        }
        logger.info("使用金豆后小票金额4=" + price + "实付金额=" + payAmount + "优惠金额=" + discountAmount);

        //更新订单
        orders = cartService.updateOrders(orders, memberInDb, ordersId, price, rate, payAmount, discountAmount, addressId, now);

        //增加订单详细
        if (addOrdersDetailsList.size() > 0) {
            for (OrdersDetails details : addOrdersDetailsList) {
//                ordersClient.thirdAddOrdersDetailsByOrdersDetails(JSON.toJSONString(details));
            }
        }

        //修改购物车详细
        if (updateCartDetailsList.size() > 0) {
            for (CartDetails cartDetails : updateCartDetailsList) {
                cartDetailsService.update(cartDetails);
            }
        }
        if (deleteCartDetailsList.size() > 0) {
            for (CartDetails cartDetails : deleteCartDetailsList) {
                cartDetailsService.deleteByCartIdAndGoodsId(cartInDb.getId(), cartDetails.getGoodsId());
            }
        }
        //修改优惠券状态为已使用(是通过new来初始化优惠券的,所以优惠券ID不为null说明使用了优惠券)
        if (couponInDb.getId() != null) {
            couponClient.thirdUpdateCouponByCoupon(JSON.toJSONString(couponInDb));
        }
        //修改会员的码豆和金豆
        memberInDb.setBeans(memberInDb.getBeans() - beans);
        memberInDb.setGoldenBeans(memberInDb.getGoldenBeans() - goldenBeans);
        memberService.update(memberInDb);

//        ordersClient.thirdAddOrdersByOrders(JSON.toJSONString(orders));
//        ordersClient.thirdAddSubOrdersBySubOrders(JSON.toJSONString(subOrders));
        HashMap<String, Object> resultMap = new HashMap<>(3);
        resultMap.put("memberId", memberInDb.getId());
        resultMap.put("ordersId", ordersId);
        resultMap.put("payAmount", payAmount);
        return new Result(StatusCode.SUCCESS_INSERTED, resultMap);
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Cart> pageList = cartService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<Cart>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, cartService.findSearch(searchMap));
    }


    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        cartService.deleteById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 判断是否是plus会员
     *
     * @param member
     * @return
     * @throws ParseException
     */
    public Boolean judgeIsPlus(Member member) throws ParseException {
        if (member == null) {
            return false;
        }
        if (!memberIsPlusZero.equals(member.getIsPlus())) {
            boolean b = belongCalendar(member.getPlusStart(), member.getPlusEnd());
            if (b) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否在某个时间区间内
     *
     * @param startTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public boolean belongCalendar(LocalDateTime startTime, LocalDateTime endTime) throws ParseException {
        LocalDateTime nowTime = LocalDateTime.now();
        if (nowTime.isBefore(startTime) || nowTime.isAfter(startTime)) {
            return true;
        }
        return false;
    }

    /**
     * 根据会员等级和店铺折扣计算该会员在这家店的折扣率
     *
     * @param memberGrade
     * @param storeRate
     * @return
     */
    public Double getMemberRate(String memberGrade, String storeRate) {
        Double vip1 = Double.parseDouble(JSON.parseObject(storeRate).get("vip1").toString());
        Double vip2 = Double.parseDouble(JSON.parseObject(storeRate).get("vip2").toString());
        if (memberIsPlusZero.equals(memberGrade)) {
            return 0.0;
        } else if (memberIsPlusOne.equals(memberGrade)) {
            return vip1;
        } else if (memberIsPlusTwo.equals(memberGrade)) {
            return vip2;
        } else {
            return 0.0;
        }
    }

    /**
     * 下单时判断优惠券是否可用
     *
     * @param couponInDb
     * @param storeId
     * @param now
     * @return
     * @throws ParseException
     */
    public boolean determineCouponAvailable(Coupon couponInDb, String storeId, LocalDateTime now) throws ParseException {
        return false;
    }

}
